#!/usr/bin/env python

import time, os, optparse, sys, re

Usage='%prog -s /var/log/appdir -d /var/archivedir -m 2880\nusage: %prog -s c:\data -d d:\dataarchive -m 43200'
p=optparse.OptionParser(usage=Usage)
p.add_option('--unix_hidden', '-u', help='Include Unix hidden files (files starting with a ".") in the archive.', action="store_true")
p.add_option('--source', '-s', help='Source Directory name you want to archive files FROM.')
p.add_option('--destination', '-d', help='Destination Directory name you want to archive files TO.')
p.add_option('--mins', '-m', help='Time frame to archive files older than in minutes.  [Default=10080 - day=1440mins, week=10080mins, 30days=43200mins].', \
    type="int", default='10080', action='store', dest='mins')

options, arguments = p.parse_args()

###Make sure our -s & -d parameters have been passed###
if not options.source:
  p.print_help()
  sys.exit()
elif not options.destination:
  p.print_help()
  sys.exit()

###'hide' regex to match hidden files
hide=re.compile(r'^[.].*$')

def filemove(file):
    ###Make sure that our file's time is older (less than) mytime and that it's actually a file (not dir)###
    if mytime >= os.stat(file).st_mtime and os.path.isfile(file):
        fullpath=os.path.join(destination, file)
        os.rename(file, fullpath)


###Make sure our source and destinations are absolute paths###
source=os.path.abspath(options.source)
destination=os.path.abspath(options.destination)
###To get "mytime" we subtract options.mins*60 from our current time (in seconds since epoch)###
mytime=time.time() - (options.mins*60)


###print line to test all args and get our calculated "mytime" converted to normal time from secs since epoch###
#print "source=%s, destination=%s, time=%s" % (destination, source, time.ctime(mytime))

###Do some error checking: ###
###If source fails then error and exit###
###If destination fails then try to create it before error and exit###
if not os.path.isdir(source):
    msg="ERROR:  %s, source must be a valid directory.\n"
    sys.exit(msg)
if not os.path.isdir(destination):
  try:
    os.makedirs(destination)
  except OSError, e:
    msg="Errno=%d:  %s - %s\n" % (e.errno, e.strerror, e.filename)
    sys.exit(msg)

###cd into our source dir, then check the mtime on each file and if it's less than mytime we move it###
try:
    os.chdir(source)
    for file in os.listdir(source):
        ###if we're passed the "-h" argument then process ALL files###
        if options.unix_hidden:
            filemove(file) 
        else:
            if not hide.match(file):
                filemove(file)
except OSError, e:
    msg="Errno=%d:  %s - %s\n" % (e.errno, e.strerror, e.filename)
    sys.exit(msg)
